package velox.jcr.mapper;

import javax.jcr.Node;
import javax.jcr.RepositoryException;

import org.springmodules.jcr.SessionFactoryUtils;


/**
 * NodeRef allows us to use uuid and node interchangeably. Any lookup/conversation between
 * the both are cached and handled transparently
 */
public class NodeRef {
	private Node node;
	private String uuid;
	
	public NodeRef(String uuid) {
		assert uuid != null;
		this.uuid = uuid;
	}
	
	public NodeRef(Node node) {
		assert node != null;
		this.node = node;
	}
	
	public Node getNode() {
		try {
			if (node == null) {
				node = UnitOfWorkHolder.get().getMapperManager().getSession().getNodeByUUID(uuid);
			}
		} catch (RepositoryException e) {
			throw SessionFactoryUtils.translateException(e);
		}
		
		return node;
	}
	
	public String getUUID() {
		try {
			if (uuid == null) uuid = node.getUUID();
		} catch (RepositoryException e) {
			throw SessionFactoryUtils.translateException(e);
		}
		return uuid;
	}
}
